package com.shelpe.services.algorithm.semiauto;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.algorithm.client.InsightWordData;
import com.shelpe.services.algorithm.client.SimbaProxyClient;
import com.shelpe.services.algorithm.client.SimbaProxyClient.CategoryDataResponse;
import com.shelpe.services.algorithm.entity.jpa.Adgroup;
import com.shelpe.services.algorithm.repository.dto.semiauto.SemiautoCondition;
import com.shelpe.services.algorithm.repository.jpa.AdgroupRepository;
import com.shelpe.services.algorithm.utils.SemiautoUtils;

@Service
public class IndustrySemiautoConditionsInitializer implements SemiautoConditionsInitializer {

	@Autowired
	private AdgroupRepository adgroupRepository;
	@Autowired
	private SimbaProxyClient simbaProxyClient;
	
	@Override
	public void run(SemiautoCondition condition, Context context) {
		
		if(condition.getSourceType() != SemiautoCondition.SOURCE_TYPE_AVERAGE_INDUSTRY){
			return;
		}
		
		if(context.getWordDatas() == null){
			Adgroup adgroup = this.adgroupRepository.findOne(context.getAdgroupID());
			if(adgroup != null && adgroup.getCategoryIDs() != null){
				String[] ida = adgroup.getCategoryIDs().split(" ");
				List<String> ids = new ArrayList<String>();
				for(String id: ida){
					ids.add(id);
				}
				if(ids.size() > 0){
					Date yesterday = DateUtils.addDays(DateUtils.truncate(new Date(), Calendar.DATE), -1);
					CategoryDataResponse res = this.simbaProxyClient.findCategoryData(ids,  
							DateFormatUtils.format(DateUtils.addDays(yesterday, - context.getInterval()), "yyyy-MM-dd"),
							DateFormatUtils.format(yesterday, "yyyy-MM-dd"),
							adgroup.getUserID());
					if(res.getRes() != null && res.getRes().getDatas() != null && res.getRes().getDatas().getWordDatas() != null){
						context.setWordDatas(res.getRes().getDatas().getWordDatas());
					}
				}
			}
		}
		
		if(context.getWordDatas() != null && context.getWordDatas().size() > 0){
			InsightWordData wordData = context.getWordDatas().get(0);
			float value = SemiautoUtils.pickup(condition.getName(), wordData);
			condition.setSourceValue(value + "");
		}
		
	}

}
